<template>
  <div>


    <div id="main" style="width:200px;height:300px;">


    </div>




  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'

import * as echarts from 'echarts';


//搜索用的
const socket = ref(null)
const errormes = ref('')
const namelist = ref([])
const valuelist = ref([])


const initecharts = () => {
  // 基于准备好的dom，初始化echarts实例
  var chartDom = document.getElementById('main');
  var myChart = echarts.init(chartDom);
  var option;

  option = {
    xAxis: {
      type: 'category',
      data: namelist.value
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: valuelist.value,
        type: 'bar'
      }
    ]
  };

  option && myChart.setOption(option);

}

const initwesockt = () => {
  socket.value = new WebSocket("ws://localhost:8000/room/1/");

  // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
  socket.value.onopen = (event) => {
    console.log(event)
    console.log("连接成功")
  }

  // 回调函数，客户端接收服务端消息
  socket.value.onmessage = (event) => {

    var data = JSON.parse(event.data)
    //data {"name":'zs',"id":1}
    errormes.value = data['errormes']
    namelist.value = data['namelist']
    valuelist.value = data['valuelist']
    initecharts()
    //mlist.value.push(data)
  }

  // // 当断开连接时，触发该函数
  // this.socket.onclose =function (event){
  // let tag = document.createElement("div");
  // tag.innerText = "[连接断开]";
  // document.getElementById("message").appendChild(tag);
  // }


}

onMounted(() => {
  initwesockt()
})
</script>
